﻿using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Office.Tools.Ribbon;
using Outlook = Microsoft.Office.Interop.Outlook;
using Word = Microsoft.Office.Interop.Word;
using Novacode;

namespace OutlookAddIn_Collaboratori
{
    public partial class RibbonContactCollaboratore : OfficeRibbon
    {
        public const string ACCOUNT_DATA_TEMPLATE_FILENAME  = "AccountData.dotx";
        public const string BOOKMARK_CreationTime           = " MERGEFIELD Создано ";
        public const string BOOKMARK_LastModificationTime   = " MERGEFIELD Изменено ";
        public const string BOOKMARK_FullName               = " MERGEFIELD Полное_имя ";
        public const string BOOKMARK_JobTitle               = " MERGEFIELD Должность ";
        public const string BOOKMARK_BusinessAddressCity    = " MERGEFIELD Город ";
        public const string BOOKMARK_OrganizationalIDNumber = " MERGEFIELD Личный_номер_орг ";
        public const string BOOKMARK_GovernmentIDNumber     = " MERGEFIELD Личный_номер ";
        public const string BOOKMARK_Email1Address          = " MERGEFIELD Эл_почта ";
        public const string BOOKMARK_NickName               = " MERGEFIELD Псевдоним ";
        public const string BOOKMARK_User2                  = " MERGEFIELD Доп_поле_2 ";
        public const string BOOKMARK_Email2Address          = " MERGEFIELD Эл_почта_2 ";
        public const string BOOKMARK_User3                  = " MERGEFIELD Доп_поле_3 ";
        public const string BOOKMARK_User4                  = " MERGEFIELD Доп_поле_4 ";
        public const string BOOKMARK_Body                   = " MERGEFIELD Заметки ";

        public RibbonContactCollaboratore()
        {
            InitializeComponent();
        }

        private void RibbonContactCollaboratore_Load(object sender, RibbonUIEventArgs e)
        {
            
            RibbonContactCollaboratore ribbon = sender as RibbonContactCollaboratore;
            Microsoft.Office.Interop.Outlook.InspectorClass inspector = ribbon.Context as Microsoft.Office.Interop.Outlook.InspectorClass;
            if (inspector != null)
            {
                OutlookInspector window = ThisAddIn.FindOutlookInspector(inspector);
                // Debug.WriteLine(window.OutlookItem.MessageClass);
                if (window.OutlookItem.MessageClass == "IPM.Contact.Collaboratore")
                {
                    GroupInvestaFinance.Visible = true;
                }
            }

        }

        private void PrintContactData_Click(object sender, RibbonControlEventArgs e)
        {
            Microsoft.Office.Interop.Outlook.InspectorClass inspector = e.Control.Context as Microsoft.Office.Interop.Outlook.InspectorClass;
            if (inspector != null)
            {
                OutlookInspector window = ThisAddIn.FindOutlookInspector(inspector);
                WordTemplateMerge2Doc(window);

            }
        }
        private void WordTemplateMerge2Doc(OutlookInspector window)
        {
            
            object oMissing = System.Reflection.Missing.Value;
            object templateFileName = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Templates) + "\\" + ACCOUNT_DATA_TEMPLATE_FILENAME;
            System.Data.SqlServerCe.SqlCeConnection co = new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=|DataDirectory|\Meta.sdf");
            templateFileName = co.DataSource;
            //\AccountData.dotx
            templateFileName = ((string)templateFileName).Remove(((string)templateFileName).Length - 8) + "AccountData.dotx.sdf";
            
            Word.Application wordApp = new Word.Application();
            wordApp.Visible = false;
            try
            {
                Word.Document wordDocument = wordApp.Documents.Add(ref templateFileName, ref oMissing, ref oMissing, ref oMissing);
                foreach (Word.Field mergeField in wordDocument.Fields)
                {
                    Word.Range range = mergeField.Code;
                    // Debug.WriteLine(">>" + range.Text + "<<");
                    mergeField.Select();
                    string outlookitemPropertyValue = " ";
                    switch (range.Text)
                    {
                        case BOOKMARK_CreationTime:
                            outlookitemPropertyValue = window.OutlookItem.CreationTime.ToString();
                            break;
                        case BOOKMARK_LastModificationTime:
                            outlookitemPropertyValue = window.OutlookItem.LastModificationTime.ToString();
                            break;
                        case BOOKMARK_FullName:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("FullName").ToString();
                            break;
                        case BOOKMARK_JobTitle:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("JobTitle").ToString();
                            break;
                        case BOOKMARK_BusinessAddressCity:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("BusinessAddressCity").ToString();
                            break;
                        case BOOKMARK_OrganizationalIDNumber:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("OrganizationalIDNumber").ToString();
                            break;
                        case BOOKMARK_GovernmentIDNumber:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("GovernmentIDNumber").ToString();
                            break;
                        case BOOKMARK_Email1Address:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("Email1DisplayName").ToString();
                            break;
                        case BOOKMARK_NickName:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("NickName").ToString();
                            break;
                        case BOOKMARK_User2:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("User2").ToString();
                            break;
                        case BOOKMARK_Email2Address:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("Email2DisplayName").ToString();
                            break;
                        case BOOKMARK_User3:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("User3").ToString();
                            break;
                        case BOOKMARK_User4:
                            outlookitemPropertyValue = window.OutlookItem.GetPropertyValue("User4").ToString();
                            break;
                        case BOOKMARK_Body:
                            outlookitemPropertyValue = window.OutlookItem.Body;
                            break;
                        default:
                            break;
                    }
                    if (String.IsNullOrEmpty(outlookitemPropertyValue))
                        wordApp.Selection.TypeText(" ");
                    else
                        wordApp.Selection.TypeText(outlookitemPropertyValue);
                    range = null;
                }

                wordApp.Visible = true;

                wordDocument = null;
                wordApp = null;
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Отсутствует шаблон "+templateFileName);
            }


        }
        /*
        public void CopyStream2Stream(Stream source, Stream target)
        {
            byte[] buffer = new byte[0x10000];
            int bytes;
            try
            {
                while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0)
                {
                    target.Write(buffer, 0, bytes);
                }
            }
            finally
            {
                target.Flush();
            }
        }

        private void WordTemplateCopy(ref string fileName)
        {
            do
            {
                fileName = Path.ChangeExtension(Path.GetTempFileName(), Guid.NewGuid().ToString() + ".dotx");
            } while (File.Exists(fileName));
            using (FileStream fsIn = File.OpenRead(@"c:\AccountData.dotx"), fsOut = File.Create(fileName, 43914)) // 43914 = размер шаблона в байтах
            {
                CopyStream2Stream(fsIn, fsOut);
                fsIn.Close();
                fsOut.Close();
            }
            Debug.WriteLine(fileName);
        }
        private void WordTemplateChangeContent(string fileName)
        {
            using (DocX document = DocX.Load(fileName))
            {
                //document.ReplaceText("ctradeorg", "cTradeOrg", false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //document.Save();
            }
        }
        private void WordTemplateViewInWord2007(string fileName)
        {
            System.Diagnostics.Process.Start("WINWORD", "\"" + fileName + "\"");
            File.Delete(fileName);
        }
        */
    }
}
